package reader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import models.action.Action;

public class ActionReader {

        public ActionReader() {
                
        }
        
        public List<Action> readActions(String filePath) throws Exception {
                List<Action> actionList = new ArrayList<Action>();
                File actionFile = new File(filePath);
                if(!actionFile.exists()) {
                    return null;
                }
                BufferedReader br = new BufferedReader(new FileReader(actionFile));
                String line;
                while ((line = br.readLine()) != null) {
                        String[] seg = line.trim().split(":");
                        if (seg.length > 3) {
                                br.close();
                                throw new Exception("In correct file format exception in "
                                + this.getClass().getName() + "#readActions()");
                        }
                        Action action = new Action();
                        if(seg.length >= 1) {
                            action.setName(seg[0]);
                        } else {
                            action.setName("");
                        }
                        if(seg.length >= 2) {
                            action.setPreCondition(parseConditions(seg[1]));
                        } else {
                            action.setPreCondition(new ArrayList<String>());
                        }
                        if(seg.length >=3) {
                            action.setPostCondition(parseConditions(seg[2]));
                        } else {
                            action.setPostCondition(new ArrayList<String>());
                        }
                        actionList.add(action);
                }
                br.close();
                return actionList;
                        
        }
        
        
        private List<String> parseConditions(String conditions) {
                String []conds = conditions.trim().split(";");
                List<String> condsList = new ArrayList<String>();
                for(String cond :conds) {
                        condsList.add(cond);
                }
                return condsList;
        }
        
}